package com.example.mfbq.handler;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mfbq.adapter.DataAdapter;
import com.example.mfbq.adapter.DataQueueAdapter;
import com.example.mfbq.R;
import com.example.mfbq.arithmetic.Process;

public class ArithmeticHandler extends Handler {
    private RecyclerView recyclerView;
    private LinearLayout queueArea;
    private ListView infoTipLv;
    private Context context;

    public ArithmeticHandler(Context context, RecyclerView recyclerView, LinearLayout queueArea, ListView infoTipLv){
        this.context = context;
        this.recyclerView = recyclerView;
        this.queueArea = queueArea;
        this.infoTipLv = infoTipLv;
    }

    @Override
    public void handleMessage(@NonNull Message msg) {
        /*
        msg.what = 0x111; 代表更新recyclerView
        msg.what = 0x112; 代表更新queueArea
        msg.what = 0x113; 代表显示结果
         */
        if(msg.what == 0x111){
            int pid = msg.arg1;//将要执行的进程
            int time = msg.arg2;
            DataAdapter adapter = (DataAdapter) recyclerView.getAdapter();
            adapter.add(pid);
            recyclerView.scrollToPosition(adapter.getItemCount()-1);
            TextView tv = new TextView(context);
            tv.setText("进程"+pid+"执行一个单位时间("+time+"--"+(time+1)+")");
            tv.setBackgroundColor(Color.WHITE);
            tv.setTextSize(12);
            infoTipLv.addFooterView(tv);
            infoTipLv.smoothScrollToPosition(infoTipLv.getCount() - 1);
        }
        if(msg.what == 0x112){
            int child = msg.arg1;//几号队列
            int pid = msg.arg2;//几号进程
            String option = (String)(msg.obj);
            String content = msg.getData().getString("content");
            LinearLayout linearLayout = (LinearLayout) this.queueArea.getChildAt(child);
            RecyclerView listView = (RecyclerView)linearLayout.getChildAt(1);
            DataQueueAdapter dataAdapter = (DataQueueAdapter) listView.getAdapter();

            TextView tv = new TextView(context);
            tv.setBackgroundColor(Color.WHITE);
            tv.setTextSize(12);

            if(option.equals("add")){
                tv.setText("进程"+pid+"插入队列"+child);
                dataAdapter.add(pid);

            }
            if(option.equals("remove")){
                tv.setText("进程"+pid+"弹出队列"+child);
                dataAdapter.remove(pid);
                if(content != null && !content.equals("")){
                    TextView ntv = new TextView(context);
                    ntv.setBackgroundColor(Color.WHITE);
                    ntv.setTextSize(12);
                    ntv.setText(content);
                    ntv.setTextColor(Color.rgb(196, 85, 243));
                    infoTipLv.addFooterView(ntv);
                    infoTipLv.smoothScrollToPosition(infoTipLv.getCount() - 1);
                }
            }

            infoTipLv.addFooterView(tv);
            infoTipLv.smoothScrollToPosition(infoTipLv.getCount() - 1);
        }
        if(msg.what == 0x113){
            Bundle data = msg.getData();
            String result = data.getString("result");
            final boolean fight = data.getBoolean("fight");
            final double art = data.getDouble("art");
            final double awrt = data.getDouble("awrt");
            final Process[] pr = (Process[])(msg.obj);
            TextView tv = new TextView(context);
            tv.setTextSize(12);
            if(fight){
                tv.setText("抢占式多级反馈队列算法执行结束\n"+result+"\n---->");
            }else{
                tv.setText("非抢占式多级反馈队列算法执行结束\n"+result+"\n---->");
            }
            tv.setTextColor(Color.BLUE);
            tv.setBackgroundColor(Color.WHITE);
            infoTipLv.addFooterView(tv);
            infoTipLv.smoothScrollToPosition(infoTipLv.getCount() - 1);

            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialogView(fight , pr, art, awrt);
                }
            });
        }
        if(msg.what == 0x114){
            DataAdapter adapter = (DataAdapter) recyclerView.getAdapter();
            adapter.add(-1);
            recyclerView.scrollToPosition(adapter.getItemCount()-1);

            TextView tv = new TextView(context);
            tv.setTextSize(12);
            tv.setText("CPU空闲");
            tv.setTextColor(Color.GREEN);
            tv.setBackgroundColor(Color.WHITE);
            infoTipLv.addFooterView(tv);
            infoTipLv.smoothScrollToPosition(infoTipLv.getCount() - 1);
        }
        if(msg.what == 0x123){
            int pid = msg.arg1;
            int time = msg.arg2;
            TextView tv = new TextView(context);
            tv.setTextSize(12);
            tv.setText("进程"+pid+"执行结束(~"+time+"~)");
            tv.setTextColor(Color.RED);
            tv.setBackgroundColor(Color.WHITE);
            infoTipLv.addFooterView(tv);
            infoTipLv.smoothScrollToPosition(infoTipLv.getCount() - 1);

        }
        if(msg.what == 0x211){
            int child = msg.arg1;//几号队列
            int pid = msg.arg2;//几号进程
            int fid = (int)(msg.obj);//抢占进程
            int time = msg.getData().getInt("time");
            int f = msg.getData().getInt("f");
            int reTime = msg.getData().getInt("reTime");

            LinearLayout linearLayout = (LinearLayout) this.queueArea.getChildAt(child);
            RecyclerView listView = (RecyclerView)linearLayout.getChildAt(1);
            DataQueueAdapter dataAdapter = (DataQueueAdapter) listView.getAdapter();
            dataAdapter.add(pid);

            TextView tv = new TextView(context);
            tv.setBackgroundColor(Color.WHITE);
            tv.setTextSize(12);
            tv.setTextColor(Color.rgb(255, 152,0));
            if(f == 1){
                tv.setText("进程"+fid+"到来，剩余服务时间最短，为 "+reTime+"\n开始抢占进程"+pid+"  ("+time+")");
            }else{
                tv.setText("进程"+fid+"到来，开始抢占进程"+pid+"  ("+time+")");
            }
            infoTipLv.addFooterView(tv);
            infoTipLv.smoothScrollToPosition(infoTipLv.getCount() - 1);

            TextView ntv = new TextView(context);
            ntv.setBackgroundColor(Color.WHITE);
            ntv.setTextSize(12);
            ntv.setText("进程"+pid+"插入队列"+child);
            infoTipLv.addFooterView(ntv);
            infoTipLv.smoothScrollToPosition(infoTipLv.getCount() - 1);
        }
        if(msg.what == 0x213){
            Bundle data = msg.getData();
            String result = data.getString("result");
            final double art = data.getDouble("art");
            final double awrt = data.getDouble("awrt");
            final String arithmetic = data.getString("arithmetic");
            final Process[] pr = (Process[])(msg.obj);
            TextView tv = new TextView(context);
            tv.setTextSize(12);
            if(arithmetic.equals("fcfs")){
                tv.setText("先来先服务算法执行结束\n"+result+"\n---->");
            }else if(arithmetic.equals("sjf")){
                boolean fight = data.getBoolean("fight");
                if(fight){
                    tv.setText("抢占式短进程优先算法执行结束\n"+result+"\n---->");
                }else{
                    tv.setText("非抢占式短进程优先算法执行结束\n"+result+"\n---->");
                }
            }else if(arithmetic.equals("hrrn")){
                tv.setText("高响应比优先算法执行结束\n"+result+"\n---->");
            }else if(arithmetic.equals("rr")){
                tv.setText("时间片轮转算法执行结束\n"+result+"\n---->");
            }
            tv.setTextColor(Color.BLUE);
            tv.setBackgroundColor(Color.WHITE);
            infoTipLv.addFooterView(tv);
            infoTipLv.smoothScrollToPosition(infoTipLv.getCount() - 1);

            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialogViewOther(pr, art, awrt, arithmetic);
                }
            });
        }
    }

    private void dialogView(boolean fight, Process[] pro, double art, double awrt){
        View view = View.inflate(context, R.layout.result_dialog, null);
        final Process[] p = pro;
        BaseAdapter adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return p.length;
            }

            @Override
            public Object getItem(int position) {
                return p[position];
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View v = View.inflate(context,R.layout.result_item, null);

                TextView resultId = v.findViewById(R.id.result_id);
                resultId.setText((p[position]).getProcessId()+"");
                TextView resultComeTime = v.findViewById(R.id.result_come_time);
                resultComeTime.setText((p[position]).getComeTime()+"");
                TextView resultServeTime = v.findViewById(R.id.result_serve_time);
                resultServeTime.setText((p[position]).getServeTime()+"");
                TextView resultCompleteTime = v.findViewById(R.id.result_complete_time);
                resultCompleteTime.setText((p[position]).getCompleteTime()+"");
                TextView resultRevolveTime = v.findViewById(R.id.result_revolve_time);
                resultRevolveTime.setText((p[position]).getRevolveTime()+"");
                TextView resultWRevolveTime = v.findViewById(R.id.result_wrevolve_time);
                resultWRevolveTime.setText(String.format("%.3f", (p[position]).getwRevolveTime()));

                return v;
            }
        };
        ListView results = view.findViewById(R.id.results);
        results.setAdapter(adapter);
        TextView averageRevolveTime = view.findViewById(R.id.average_revolve_time);
        averageRevolveTime.setText("平均周转时间为：" + String.format("%.3f", art));
        TextView averageWRevolveTime = view.findViewById(R.id.average_wrevolve_time);
        averageWRevolveTime.setText("平均带权周转时间为：" + String.format("%.3f", awrt));

        String title = "";
        if(fight){
            title = "抢占式多级反馈队列算法";
        }else{
            title = "非抢占式多级反馈队列算法";
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle(title)
                .setView(view);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }
    private void dialogViewOther(Process[] pro, double art, double awrt, String arithmetic){
        View view = View.inflate(context, R.layout.result_dialog, null);
        final Process[] p = pro;
        BaseAdapter adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return p.length;
            }

            @Override
            public Object getItem(int position) {
                return p[position];
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View v = View.inflate(context,R.layout.result_item, null);

                TextView resultId = v.findViewById(R.id.result_id);
                resultId.setText((p[position]).getProcessId()+"");
                TextView resultComeTime = v.findViewById(R.id.result_come_time);
                resultComeTime.setText((p[position]).getComeTime()+"");
                TextView resultServeTime = v.findViewById(R.id.result_serve_time);
                resultServeTime.setText((p[position]).getServeTime()+"");
                TextView resultCompleteTime = v.findViewById(R.id.result_complete_time);
                resultCompleteTime.setText((p[position]).getCompleteTime()+"");
                TextView resultRevolveTime = v.findViewById(R.id.result_revolve_time);
                resultRevolveTime.setText((p[position]).getRevolveTime()+"");
                TextView resultWRevolveTime = v.findViewById(R.id.result_wrevolve_time);
                resultWRevolveTime.setText(String.format("%.3f", (p[position]).getwRevolveTime()));

                return v;
            }
        };
        ListView results = view.findViewById(R.id.results);
        results.setAdapter(adapter);
        TextView averageRevolveTime = view.findViewById(R.id.average_revolve_time);
        averageRevolveTime.setText("平均周转时间为：" + String.format("%.3f", art));
        TextView averageWRevolveTime = view.findViewById(R.id.average_wrevolve_time);
        averageWRevolveTime.setText("平均带权周转时间为：" + String.format("%.3f", awrt));

        String title = "";
        if(arithmetic.equals("fcfs")){
            title = "先来先服务算法";
        }else if(arithmetic.equals("sjf")){
            title = "短进程优先算法";
        }else if(arithmetic.equals("hrrn")){
            title = "高响应比优先算法";
        }else if(arithmetic.equals("rr")){
            title = "时间片轮转算法";
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle(title)
                .setView(view);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }
}